package org.xp.judgeplatform.config;

import lombok.Data;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.ai.vectorstore.redis.RedisVectorStore;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPooled;

@Configuration
@EnableAutoConfiguration(exclude = {
    org.springframework.ai.vectorstore.redis.autoconfigure.RedisVectorStoreAutoConfiguration.class
})
@EnableConfigurationProperties(RedisVectorConfig.RedisVectorStoreProperties.class)
public class RedisVectorConfig {

    private final RedisVectorStoreProperties properties;

    public RedisVectorConfig(RedisVectorStoreProperties properties) {
        this.properties = properties;
    }

    @Bean
    public VectorStore vectorStore(EmbeddingModel embeddingModel) {
        JedisPooled jedisPooled;
        if (properties.getPassword() != null && !properties.getPassword().isEmpty()) {
            jedisPooled = new JedisPooled(properties.getHost(), properties.getPort(), null, properties.getPassword());
        } else {
            jedisPooled = new JedisPooled(properties.getHost(), properties.getPort());
        }

        return RedisVectorStore.builder(jedisPooled, embeddingModel)
                .initializeSchema(properties.isInitializeSchema())
                .indexName(properties.getIndexName())
                .prefix(properties.getPrefix())
                .build();
    }

    @Data
    @ConfigurationProperties(prefix = "spring.ai.vectorstore.redis")
    public static class RedisVectorStoreProperties {
        private String host = "localhost";
        private int port = 6379;
        private String password = "";
        private int database = 1;
        private boolean initializeSchema = true;
        private String indexName = "judge-index";
        private String prefix = "default:";
    }
}
